export class JsStorage implements Storage {
  constructor(private storage: Storage) { }

  /**
   * 缓存存储 
   * @param key //缓存key 名称
   * @param value //缓存key 值
   * @param Tscope //作用域
   * @returns 
   */
  setItem(key: string, value: any, Tscope?) {
    let storage = this.storage
    if (!key) {
      console.error("cache 'key' is undefined");
      return;
    }
    if (Tscope) {
      value['Tscope'] = Tscope
    }
    storage.setItem(key, JSON.stringify(value));
  }


  getItem(key: string) {
    const obj = this.storage.getItem(key)
    if (obj && obj !== 'undefined' && obj !== 'null') {
      return JSON.parse(obj)
    }
    return null
  }


  clear() {
    return this.storage.clear()
  }

  get length(): number {
    return this.storage.length
  }

  key(index: number): string {
    return this.storage.key(index)
  }

  /**
   * 移除缓存数据
   * @param key 
   * @param Tscope //作用域
   * @returns 
   */
  removeItem(key: string): void {
    return this.storage.removeItem(key)
  }

  /**
   * 清除指定缓存列表
   * @param Tscope 作用域
   */
  removeItemlist(Tscope) {
    const storage = this.storage
    for (let i = 0; i < storage.length; i++) {
      let field = storage.key(i);
      let val = storage.getItem(field);
      try {
        let data = JSON.parse(val);
        if (data.Tscope == Tscope) {
          storage.removeItem(field);
        }
      } catch (err) {
        console.error(err);
      }
    }
  }

}
